package hbase;

import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Increment;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/**
 * Created by spark on 16-10-17.
 */
public class CounterTest extends Configured implements Tool{
    @Override
    public int run(String[] args) throws Exception {

        Connection conn = ConnectionFactory.createConnection(getConf());
        Table table = conn.getTable(TableName.valueOf("counters"));


        singleCounterTest(table);

        incrementTest(table);


        return 0;
    }

    private void incrementTest(Table table) throws IOException {
        Increment incre = new Increment(Bytes.toBytes("20161017"));

        incre.addColumn(Bytes.toBytes("weekly"), Bytes.toBytes("clicks"), 2);

        incre.addColumn(Bytes.toBytes("monthly"), Bytes.toBytes("clicks"), 23);

        incre.addColumn(Bytes.toBytes("daily"), Bytes.toBytes("clicks"), 12);

//        incre.setTimeRange(4, 5);

        table.increment(incre);
    }

    private void singleCounterTest(Table table) throws IOException {
        long counter1 = table.incrementColumnValue(Bytes.toBytes("20161017"),
                Bytes.toBytes("daily"), Bytes.toBytes("hits"), 1);
        long counter2 = table.incrementColumnValue(Bytes.toBytes("20161017"),
                Bytes.toBytes("daily"), Bytes.toBytes("hits"), 23);

        long counter3 = table.incrementColumnValue(Bytes.toBytes("20161017"),
                Bytes.toBytes("daily"), Bytes.toBytes("hits"), 0);

        long counter4 = table.incrementColumnValue(Bytes.toBytes("20161017"),
                Bytes.toBytes("daily"), Bytes.toBytes("hits"), -1);
    }

    public static void main(String[] args) throws Exception {
        int exitCode = ToolRunner.run(new CounterTest(), args);
        System.exit(exitCode);
    }
}
